package com.example.activelifecycletest.persistence.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

import androidx.annotation.Nullable;

/**
 * SQLite数据库操作
 * @author zhangding
 * @date 2022年04月25日15:28:54
 */
public class MyDatabaseHelper extends SQLiteOpenHelper {
    public static final String CREATE_BOOK_TABLE = "create table book(" +
                                                   " id integer primary key autoincrement," +
                                                   " author text," +
                                                   " price real," +
                                                   " pages integer," +
                                                   " name text)";
    public static final String CREATE_CATEGORY_BOOK = "create table category(" +
                                                    " id integer primary key autoincrement," +
                                                    " category_name text," +
                                                    " category_code integer)";
    private Context context;
    public MyDatabaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(CREATE_BOOK_TABLE);
        sqLiteDatabase.execSQL(CREATE_CATEGORY_BOOK);
        Toast.makeText(context, "创建成功！", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("drop table if exists book");
        sqLiteDatabase.execSQL("drop table if exists category");
        onCreate(sqLiteDatabase);
    }
}
